package com.hsylient.javase.chapter14;

import lombok.SneakyThrows;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

public class RSASignUtil {

    @SneakyThrows
    public static void main(String[] args) {
        String content = "大家好我叫黄涛";

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 生成私钥
        PrivateKey privateKey = keyPair.getPrivate();
        // 公钥
        PublicKey publicKey = keyPair.getPublic();

        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey);
        signature.update(content.getBytes(StandardCharsets.UTF_8));
        byte[] sign = signature.sign();
        // 签名
        String xxxx = Base64.getEncoder().encodeToString(sign);
        System.out.println(xxxx);

        Signature signature2 = Signature.getInstance("MD5withRSA");
        signature2.initVerify(publicKey);
        signature2.update(content.getBytes(StandardCharsets.UTF_8));

        boolean verify = signature2.verify(Base64.getDecoder().decode(xxxx));
        System.out.println(verify);
    }
}
